<?php

	class UsersController extends AppController {
		var $name = 'Users';
		var $uses = array('User');
		var $components = array('Email');
		
		var $publicAction = array('profile', 'signup', 'logout', 'forgot_pw');
		
	/*
	 * Use this in the JavaScript code that is served to your users
	 */
		var $reCapchaPublicKey = '6LeGxbwSAAAAACkAqyhrz_jBglNe9psOboVkizO-';
	/*
	 * Use this when communicating between your server and our server.
	 * Because this key is a global key, it is OK if the private key is distributed to multiple users. 
	 */
		var $reCapchaPrivateKety = '6LeGxbwSAAAAAH18GCczZXWbQq_cIbXJQAcDkaKL';
		
		var $reCapchaResponse = null;
		var $reCapchaError = null;
		var $reCapchaValid = false;
		
		function profile($id = null) {
			$conditions = array();
			
			if (!empty($this->params['shortcut'])) {
				$conditions['User.shortcut'] = $this->params['shortcut'];
			}
			else {
				if ($this->Session->check('Auth.User')) {
					$conditions['User.id'] = $this->Session->read('Auth.User.id');
				}
				else {
					$this->redirect(array('controller' => 'home', 'action' => 'index'));
				}
			}
			
			$data = $this->User->find(
				'first',
				array(
					'conditions' => array_merge(
						array(
							'User.active' => 1,
							'User.disabled' => 0,
							'User.deleted' => 0
						),
						$conditions
					),
					'fields' => array(
						'id',
						'shortcut',
						'last_logon',
						'created'
					),
					'contain' => array(
						'Profile' => array(
							'firstname',
							'lastname'
						),
						'Shop' => array(
							'slug',
							'name'
						)
					),
					'recursive' => 1
				)
			);
			
			$this->pageTitle = $data['Profile']['name'] = sprintf('%s %s', end(array_reverse(explode(' ', $data['Profile']['firstname']))), end(array_reverse(explode(' ', $data['Profile']['lastname']))));
			
			$this->set(compact('data'));
		}
		
		function people() {
			$this->profile();
			$this->render('profile');
		}
		
		function signup() {
			$this->pageTitle = __('Crear tu cuenta', true);
			
			App::import('Vendor', 'recaptchalib');
			
			if ($this->Session->check('NewAccount')) {
				$this->set('info', $this->Session->read('NewAccount'));
				$this->render('signup_sucess');
				$this->Session->delete('NewAccount');
			} else {
				if (!empty($this->data)) {
					$this->__create();
				}
				else {
					if (!empty($this->params['url']['shortcut'])) {
						$this->data['Shop']['slug'] = $this->params['url']['shortcut'];
					}
				}
				$industries = $this->User->Shop->Industry->find('list', array('conditions' => array('disabled' => 0)));
				$this->set('industries', $industries);
				
				$this->set('captcha', recaptcha_get_html($this->reCapchaPublicKey, $this->reCapchaError));
			}
		}
		
		function login() {
			$this->pageTitle = __('Entrar', true);
			
			if ($this->Session->check('User.valid')) {
				$this->redirect(Configure::read('Site.Url.main') . Router::url(array('controller' => 'users', 'action' => 'profile', 'shortcut' => $this->Session->read('User.shortcut'))));
			}
				
			if(!empty($this->data)) {
				
				# verified email
				if (eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $this->data['User']['username'])) {
					$user = $this->User->find(
						'first',
						array(
							'conditions' => array(
								'User.username' => $this->data['User']['username'],
								'User.disabled' => 0,
								'User.deleted' => 0
							),
							'fields' => array(
								'User.id',
								'User.shortcut',
								'User.username',
								'User.password',
								'User.last_logon',
								'User.disabled'
							),
							'recursive' => -1
						)
					);
				}
				# verified shop alias
				else {
					$shop = $this->User->Shop->find(
						'first',
						array(
							'conditions' => array(
								'Shop.alias' => $this->data['User']['username'],
								'Shop.disabled' => 0,
								'Shop.deleted' => 0
							),
							'fields' => array(
								'user_id'
							),
							'recursive' => -1
						)
					);
					
					$user = $this->User->find(
						'first',
						array(
							'conditions' => array(
								'User.id' => $shop['Shop']['user_id']
							),
							'fields' => array(
								'User.id',
								'User.shortcut',
								'User.username',
								'User.password',
								'User.last_logon',
								'User.disabled'
							),
							'recursive' => -1
						)
					);
				}
				
				if (!empty($user)) {
					if ($user['User']['password'] == Security::hash($this->data['User']['password'], 'sha1', true)) {
						if (!$user['User']['disabled']) {
							$this->User->id = $user_id = $user['User']['id'];
							
							$this->User->saveField('last_logon', date('Y-m-d H:i:s'));
							
							$profile = $this->User->Profile->find(
								'first',
	 							array(
	 								'conditions' => array(
	 									'Profile.user_id' => $user_id
	 								),
									'fields' => array(
										'Profile.id',
										'Profile.firstname',
										'Profile.lastname',
										'Profile.birthdate',
										'Profile.gender',
										'Profile.email',
										'Profile.telephone',
										'Profile.mobile',
										'Profile.image',
										'CONCAT(\''. Configure::read('Site.Url.static') . '/media/profile/\', Profile.id, \'/\', REPLACE(Profile.image,\'.\',\'_tiny.\')) AS avatar_tiny', // 16x16
										'CONCAT(\''. Configure::read('Site.Url.static') . '/media/profile/\', Profile.id, \'/\', REPLACE(Profile.image,\'.\',\'_small.\')) AS avatar_small', // 24x24
										'CONCAT(\''. Configure::read('Site.Url.static') . '/media/profile/\', Profile.id, \'/\', REPLACE(Profile.image,\'.\',\'_medium.\')) AS avatar_medium', // 48x48
										'CONCAT(\''. Configure::read('Site.Url.static') . '/media/profile/\', Profile.id, \'/\', REPLACE(Profile.image,\'.\',\'_bigger.\')) AS avatar_bigger' // 73x73
									)
								)
							);
							
							$name = sprintf('%s %s', end(array_reverse(explode(' ', $profile['Profile']['firstname']))), end(array_reverse(explode(' ', $profile['Profile']['lastname']))));
							
							$profile['Profile'] = array_merge($profile['Profile'], $profile[0], compact('name'));
							
							
							$this->Session->write('User', $user['User']);
							$this->Session->write('User.valid', true);
							//$this->Cookie->write('User.User', $user['User'], false);
							
							unset($user['User']);
							
							$this->Session->write('User.Profile', $profile['Profile']);
							$this->Cookie->write('User.Profile', $profile['Profile'], false);
							unset($profile['Profile']);
							
							$shops = $this->User->Shop->find(
								'all',
								array(
									'conditions' => array(
										'Shop.user_id' => $user_id,
										'Shop.disabled' => 0
									),
									'fields' => array(
										'id',
										'alias',
										'name',
										'domain'
									),
									'order' => 'Shop.created ASC',
									'recursive' => -1
								)
							);
							
							if (!empty($shops)) {
								$this->Session->write('User.Shop', $shops);
								//$this->Cookie->write('User.Shop', $shops, false);
								$this->redirect('http://'.$shops[0]['Shop']['domain'].'/dashboard');
								//$this->redirect(array('shop' => $shop[0]['Shop']['slug'], 'controller' => 'shops', 'action' => 'dashboard_index'));
							}
							unset($shops);
							
							$this->redirect(Configure::read('Site.Url.main') . Router::url(array('controller' => 'users', 'action' => 'profile', 'shortcut' => $user['User']['shortcut'])));
						} else {
							$this->Session->setFlash(__('Lamentablemente el usuario se encuentra deshabilitado, por favor contactate con la administración de Plasa.', true));
						}
					}
					else {
						$this->Session->setFlash(__('Por favor, vuelve a introducir la clave, asegúrate de que la tecla Bloq Mayús no esté activada é inténtalo de nuevo.', true));
					}
				}
				else {
					$this->Session->setFlash(__('El correo electrónico y clave son incorrectos, las claves usadas en Plasa distinguen entre mayúsculas y minúsculas, comprueba la tecla Bloq Mayús.', true), null, array('class' => 'warning'));
					$this->Session->write('LoginAttempt.Message', __('Si no recuerdas tu clave puedes recuperarla aquí.', true));
				}
				unset($this->data['User']['password']);
			}
		}
		
		function logout() {
			$this->Session->delete('Auth');
			$this->redirect(array('controller' => 'home', 'action' => 'index'));
		}
		
		function settings() {
			$this->pageTitle = __('Información Personal', true);
			$this->data = $this->User->read(null, $this->Session->read('Auth.User.id'));
		}
		
		function forgot_pw() {
			if (!empty($this->data)) {
				
			}
			
			$this->pageTitle = __('Reestablece tu contraseña', true);
		}
		
		private function __create() {
			$this->User->recursive = 1;
			
			$this->User->set($this->data);
			$this->User->Profile->set($this->data);
			
			$this->User->validate = array(
				'usr' => array(
					'rule' => 'email',
					'message' => __('La dirección de correo electrónico debe ser correcta.', true)
				),
				'pwd' => array(
					'rule' => '/.+/',
					'message' => __('Debes indicar una clave para ingresar a tu cuenta.', true)
				),
				'recaptcha' => array(
					'rule' => '/.+/',
					'message' => __('Debes agregar las 2 palabras que estan arriba.', true)
				)
			);
			
			if (!empty($this->data['User']['usr'])) {
				if ($this->User->hasAny(array('username' => $this->data['User']['usr']))) {
					$this->User->invalidate('usr', __('Ya existe una cuenta con este correo electrónico.', true));
					$this->set('username_exist', true);
				}
			}
			
			$this->User->Profile->validate = array(
				'firstname' => array(
					'rule' => '/.+/',
					'message' => __('Es necesario que nos indiques tus nombres.', true)
				),
				'lastname' => array(
					'rule' => '/.+/',
					'message' => __('Es necesario que nos indiques tus apellidos.', true)
				)
			);
			
			$__create_shop = false;
			if ($this->data['Shop']['iwant']) {
				$__create_shop = true;
				$this->User->Shop->set($this->data);
				$this->User->Shop->Industry->set($this->data);
				
				$this->User->Shop->validate = array(
					/*'name' => array(
						'rule' => '/.+/',
						'message' => __('Es importante que indiques el nombre de tu tienda.', true)
					),*/
					'slug' => array(
						'rule' => '/^[0-9a-z_-]+$/i',
						'message' => __('La dirección de la tienda contiene caracteres no permitidos.', true)
					),
					/*
					'industry' => array(
						'rule' => 'checkIndustry',
						'message' => __('Es importante saber a que rubro esta asociado tu negocio.', true)
					)*/
				);
				
				if (!empty($this->data['Shop']['slug'])) {
					if ($this->User->Shop->hasAny(array('slug' => $this->data['Shop']['slug']))) {
						$this->User->Shop->invalidate('slug', __('Ya existe una tienda con esta dirección, prueba con otra.', true));
					}
				}
				
				//if (empty($this->data['Shop']['industry'])) {
				if (empty($this->data['Industry']['Industry'])) {
					$this->User->Shop->invalidate('industry', __('Es importante saber a que rubro esta asociado tu negocio.', true));
				} else {
					//$this->data['Industry']['Industry'] = $this->data['Shop']['industry'];
				}
			}
			
			$this->User->Profile->invalidFields();
			$this->User->Shop->invalidFields();
			
			$this->__recaptcha();
			
			if ($this->User->validates() AND $this->User->Profile->validates()) {
				$__create_account = true;
				
				if ($__create_shop && !$this->User->Shop->validates()) {
					$__create_shop = false;
					$__create_account = false;
				}
				
				if ($__create_account) {
					$this->data['User']['username'] = $this->data['User']['usr'];
					$this->data['User']['password'] = Security::hash($this->data['User']['pwd'], 'sha1', true);
					$this->data['User']['active'] = 1;
					$this->User->save($this->data, false);
					
					$this->data['User']['shortcut'] = $this->data['Shop']['user_id'] = $this->data['Profile']['user_id'] = $this->User->id;
					$this->data['Profile']['email'] = $this->data['User']['usr'];
										
					$this->User->save($this->data);
					$this->User->Profile->save($this->data, false);
					
					if ($__create_shop) {
						$this->data['Shop']['name'] = sprintf('%s\'s', $this->data['Shop']['slug']);
						$this->User->Shop->save($this->data, array('validate' => false));

						$this->Email->from = 'Minicatalogo.cl <no-reply@minicatalogo.cl>';
						$name = end(array_reverse(explode(' ', $this->data['Profile']['firstname'])));
						$this->Email->to = sprintf('%s <%s>', $name, $this->data['User']['usr']);
						$this->Email->subject = __('Bienvenido a Minicatalogo.cl', true);
						$this->Email->template = 'signup_welcome';
						$this->Email->sendAs = 'html';
						
						$this->Email->delivery = 'mail';
						
						$this->set('name', $name);
						
						$this->Email->send();
						
						// Crear portada de la tienda
						/*
						$post = array();
						$post['Post']['shop_id'] = $this->User->Shop->id;
						$post['Post']['user_id'] = $this->data['Shop']['user_id'];
						$post['Post']['title'] = sprintf(__('Te damos la bienvenida a nuestra tienda  "%s"', true), $this->data['Shop']['name']);
						$post['Post']['content'] = sprintf(__('Nuestra tienda contiene diferentes productos asociados a los rubros de %s, navega y encuentra lo que estas buscando.', true), implode(',', $this->data['Shop']['industry']));
						$post['Post']['type'] = 'pages';
						$post['Post']['front_page'] = 1;
						$post['Post']['publish'] = date('Y-m-d H:i:s');
						$this->User->Post->save($post);
						unset($post['Post']['front_page']);
						
						$this->User->Post->id = null;
						// Crear sección nosotros
						$post['Post']['shop_id'] = $this->User->Shop->id;
						$post['Post']['user_id'] = $this->data['Shop']['user_id'];
						$post['Post']['title'] = __('Nosotros', true);
						$post['Post']['content'] = __('Pronto información sobre nuestra tienda y quienes somos.', true);
						$this->User->Post->save($post);
						*/
						
						/*
						$conf = array();
						$conf['Configuration']['option'] = 'menu_top_pages';
						$conf['Configuration']['value'] = serialize(
							array(
								$this->User->Post->slug => array(
									$post['Post']['title'] => array('shop' => $this->data['Shop']['slug'], 'controller' => 'posts', 'action' => 'details', 'type' => 'pages', 'slug' => $this->User->Post->slug)
								)
							)
						);
						
						$this->User->Shop->Configuration->save($conf);
						*/
					}
					
					$this->Session->write('NewAccount', $this->data);
					//$this->redirect(array('controller' => 'users', 'action' => 'signup'));
					$this->redirect(array('controller' => 'users', 'action' => 'login'));

					unset($this->data);
				}
			}
		}
		
		private function __recaptcha()
		{
			if (!empty($this->params['form']['recaptcha_challenge_field'])) {
				$this->reCapchaResponse = recaptcha_check_answer(
					$this->reCapchaPrivateKety,
					$_SERVER['REMOTE_ADDR'],
					$this->params['form']['recaptcha_challenge_field'],
					$this->data['User']['recaptcha']
				);
				if ($this->reCapchaResponse->is_valid) {
					$this->reCapchaValid = true;
				} else {
					$this->reCapchaError = $this->reCapchaResponse->error;
					$this->User->invalidate('recaptcha', __('Las palabras ingresadas no son correctas, ingresa nuevamente las palabras.', true));
				}
			}
		}

		function dashboard_settings()
		{
			
		}
		
		function dashboard_personal()
		{
			
		}
		
		function dashboard_notifications()
		{
			
		}
		
		function dashboard_change_pw()
		{
			
		}
	}

?>